package com.uinnova.product.eam.service.cj.service.impl;

import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.google.common.collect.Lists;
import com.uinnova.product.eam.base.cj.BaseEntity;
import com.uinnova.product.eam.comm.model.es.AppSquareConfig;
import com.uinnova.product.eam.comm.model.es.EamAttention;
import com.uinnova.product.eam.comm.model.es.EamRecentlyView;
import com.uinnova.product.eam.model.RecentlyViewBo;
import com.uinnova.product.eam.model.asset.AssetCiDetailInfoDTO;
import com.uinnova.product.eam.model.cj.domain.DirRelationPlan;
import com.uinnova.product.eam.model.cj.domain.PlanDesignInstance;
import com.uinnova.product.eam.model.cj.enums.PlanStatusEnum;
import com.uinnova.product.eam.model.cj.vo.DirVo;
import com.uinnova.product.eam.model.cj.vo.ESDiagramDirPlanVO;
import com.uinnova.product.eam.model.cj.vo.PublishedDiagramPlanVO;
import com.uinnova.product.eam.model.constants.Constants;
import com.uinnova.product.eam.model.constants.DiagramConstant;
import com.uinnova.product.eam.model.dto.AttentionDto;
import com.uinnova.product.eam.model.dto.EamCategoryDTO;
import com.uinnova.product.eam.model.enums.AssetType;
import com.uinnova.product.eam.model.enums.HandleTypeEnum;
import com.uinnova.product.eam.model.vo.AttentionVo;
import com.uinnova.product.eam.model.vo.MineAssetsReq;
import com.uinnova.product.eam.model.vo.MineAssetsVo;
import com.uinnova.product.eam.model.vo.MinePlanQueryVo;
import com.uinnova.product.eam.service.AppSquareConfigSvc;
import com.uinnova.product.eam.service.EamCategorySvc;
import com.uinnova.product.eam.service.ICISwitchSvc;
import com.uinnova.product.eam.service.IEamCIClassApiSvc;
import com.uinnova.product.eam.service.asset.IAttentionSvc;
import com.uinnova.product.eam.service.asset.IRecentlyViewSvc;
import com.uinnova.product.eam.service.cj.dao.DirRelationPlanDao;
import com.uinnova.product.eam.service.cj.dao.PlanDesignInstanceDao;
import com.uinnova.product.eam.service.cj.service.DirDiagramPlanService;
import com.uinnova.product.eam.service.cj.service.DirRelationPlanService;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.exception.BusinessException;
import com.uinnova.product.vmdb.comm.i18n.MessageUtil;
import com.uinnova.product.vmdb.comm.model.ci.CCcCi;
import com.uinnova.product.vmdb.comm.model.ci.CcCi;
import com.uinnova.product.vmdb.comm.model.ci.CcCiClass;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiInfo;
import com.uinnova.product.vmdb.provider.ci.bean.CiGroupPage;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.model.CVcDiagram;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.base.diagram.comm.model.ESSimpleDiagramDTO;
import com.uinnova.project.service.eam.ESDiagramSvc;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.cmdb.base.ESCIClassInfo;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.cmdb.query.ESCISearchBean;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.UserInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description: 文件夹 + 制品 + 方案接口
 * @author: Lc
 * @create: 2022-02-23 17:17
 */
@Service
@Slf4j
public class DirDiagramPlanServiceImpl implements DirDiagramPlanService {

    @Resource
    private PlanDesignInstanceService planDesignInstanceService;

    @Resource
    private IUserApiSvc userApiSvc;

    @Resource
    private DirRelationPlanDao dirRelationPlanDao;

    @Resource
    private DirRelationPlanService dirRelationPlanService;

    @Resource
    private PlanDesignInstanceDao planDesignInstanceDao;

    @Resource
    private ICISwitchSvc ciSwitchSvc;

    @Resource
    private IAttentionSvc attentionSvc;

    @Resource
    private IRecentlyViewSvc recentlyViewSvc;

    @Resource
    private ESDiagramSvc esDiagramSvc;
    @Resource
    private ESDiagramApiClient diagramApiClient;
    @Resource
    private EamCategorySvc categorySvc;
    @Resource
    IEamCIClassApiSvc ciClassApiSvc;

    @Resource
    private AppSquareConfigSvc squareConfigSvc;

    @Override
    public List<CcCi> getPlanAssertName(Long planId) {
        PlanDesignInstance planDesignInstance = planDesignInstanceDao.getById(planId);
        List<String> ciCodeList = planDesignInstance.getCiCodeList();
        //调用伏羲的接口实现CcCi列表查询
        CCcCi cdt = new CCcCi();
        cdt.setCiCodes(ciCodeList.toArray(new String[0]));
        List<CcCi> ciList = ciSwitchSvc.queryCiList(SysUtil.getCurrentUserInfo().getDomainId(), cdt, null, true, LibType.DESIGN);
        if (!CollectionUtils.isEmpty(ciList)) {
            return ciList;
        }
        return Collections.emptyList();
    }

    @Override
    @Deprecated
    public ESDiagramDirPlanVO getBuildAssert(MineAssetsVo mineAssetsVo, String like) {
        AttentionVo buildAssets = getBuildAssets(mineAssetsVo);
        if (buildAssets != null) {
            //架构设计查看我的发布的视图和方案
            if (mineAssetsVo.getHandleType() == 1) {
                return queryMyPublished(buildAssets);
            } else if (mineAssetsVo.getHandleType() == 2) {
                //架构设计查看我的关注的视图和方案
                return queryMyAttention(buildAssets, like);
            } else {
                //架构设计查看我的最近查看视图和方案
                return queryMyRecentView(buildAssets);
            }
        }
        return null;
    }

    public ESDiagramDirPlanVO getBuildAssertNew(MineAssetsReq req) {
        BinaryUtils.checkNull(req, "参数");
        BinaryUtils.checkNull(req.getHandleType(), "操作类型");
        Set<Long> categoryIds = new HashSet<>();
        List<Long> parentIds = new ArrayList<>();
        if (req.getRootId() != null) {
            parentIds = Stream.of(req.getRootId()).collect(Collectors.toList());
        } else {
            List<EamCategoryDTO> libraries = categorySvc.queryDesignPermissionRootList(SysUtil.getCurrentUserInfo().getLoginCode());
            parentIds = libraries.stream().map(EamCategoryDTO::getId).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(parentIds)) {
            return new ESDiagramDirPlanVO();
        }
        List<EamCategoryDTO> categories = categorySvc.queryChildsWithFileReadPemissonByParentIds(parentIds, LibType.DESIGN);
        List<EamCategoryDTO> categoryPrivates = categorySvc.queryChildsWithFileReadPemissonByParentIds(Arrays.asList(0L), LibType.PRIVATE);
        categories.addAll(categoryPrivates);
        if (CollectionUtils.isEmpty(categories)) {
            return new ESDiagramDirPlanVO();
        }
        categoryIds = categories.stream().map(EamCategoryDTO::getId).collect(Collectors.toSet());
        switch (req.getHandleType()) {
            case MINE_PUBLISH:
                return this.queryMyPublished(req, categoryIds);
            case MINE_ATTENTION:
                return this.queryMyAttention(req, categoryIds);
            case RECENTLY_VIEW:
                return this.queryMyRecentView(req, categoryIds);
        }
        return null;
    }

    private ESDiagramDirPlanVO queryMyPublished(MineAssetsReq req, Set<Long> categoryIds) {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        UserInfo userInfo = userApiSvc.getUserInfoByLoginCode(SysUtil.getCurrentUserInfo().getLoginCode());
        if (userInfo == null) {
            userInfo = new UserInfo();
        }
        //我发布的视图
        BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
        diagramQuery.must(QueryBuilders.termQuery("isOpen", 1));
        diagramQuery.must(QueryBuilders.termQuery("creator.keyword", SysUtil.getCurrentUserInfo().getLoginCode()));
        diagramQuery.must(QueryBuilders.termQuery("historyVersionFlag", 1));
        Page<ESDiagram> diagramPage = diagramApiClient.selectListByQuery(1, 3000, diagramQuery);
        //我发布的视图
        this.fillMyPublishedDiagramInfo(diagramPage.getData(), req, categoryIds, userInfo, result);
        //我发布的方案
        List<PlanDesignInstance> planDesignList = planDesignInstanceService.queryMyPublishPlan();
        List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
        this.fillMyPublishedPlanInfo(planDesignList, req, categoryIds, userInfo, myAttentionPlans, result);
        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getModifyTime() - o1.getModifyTime()));
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    private void fillMyPublishedDiagramInfo(List<ESDiagram> diagrams, MineAssetsReq req
            , Set<Long> categoryIds, UserInfo userInfo, List<PublishedDiagramPlanVO> result) {
        if (CollectionUtils.isEmpty(diagrams)) {
            return;
        }
        Map<String, ESDiagram> myAttentionDiagramMap = this.queryMyAttentionDiagramMap();
        for (ESDiagram diagram : diagrams) {
            Boolean matchFilter = this.matchFilter(req, diagram.getName(), categoryIds, diagram.getDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            if (myAttentionDiagramMap.containsKey(diagram.getDEnergy())) {
                diagram.setIsAttention(DiagramConstant.IS_ATTENTION);
            }
            publishedDiagramPlanVO.setCreator(userInfo);
            publishedDiagramPlanVO.setDiagram(diagram);
            publishedDiagramPlanVO.setAssetType(AssetType.DIAGRAM);
            publishedDiagramPlanVO.setModifyTime(diagram.getModifyTime());
            result.add(publishedDiagramPlanVO);
        }
    }

    private void fillMyPublishedPlanInfo(List<PlanDesignInstance> planDesignList, MineAssetsReq req
            , Set<Long> categoryIds, UserInfo userInfo, List<Long> myAttentionPlans, List<PublishedDiagramPlanVO> result) {
        if (CollectionUtils.isEmpty(planDesignList)) {
            return;
        }
        //历史版本 + 最新版本
        Map<String, List<PlanDesignInstance>> planHistoryMap = this.queryPlanHistory(planDesignList);
        for (PlanDesignInstance plan : planDesignList) {
            Boolean matchFilter = this.matchFilter(req, plan.getName(), categoryIds, plan.getAssetsDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            publishedDiagramPlanVO.setCreator(userInfo);
            String dirType = plan.getDirType() == null ? "" : plan.getDirType().toString();
            String key = plan.getBusinessKey() + dirType;
            if (planHistoryMap.containsKey(key)) {
                plan.setVersion(planHistoryMap.get(key).size());
            }
            publishedDiagramPlanVO.setPlanDesignInstance(plan);
            publishedDiagramPlanVO.setAssetType(AssetType.SCHEME);
            publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
            if (myAttentionPlans.contains(plan.getId())) {
                publishedDiagramPlanVO.setIsAttention(1);
            }
            result.add(publishedDiagramPlanVO);
        }
    }

    private ESDiagramDirPlanVO queryMyAttention(MineAssetsReq req, Set<Long> categoryIds) {
        AttentionVo attentionVo = attentionSvc.findAttentionList(1, 3000, SysUtil.getCurrentUserInfo().getId());
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        if (CollectionUtils.isEmpty(attentionVo.getDiagramList()) && CollectionUtils.isEmpty(attentionVo.getPlanDesignList())) {
            return esDiagramDirPlanVO;
        }
        Map<String, UserInfo> userInfoMap = attentionVo.getUserInfoMap();
        Map<Long, Long> attentionSort = attentionVo.getAttentionList().stream().collect(
                Collectors.toMap(EamAttention::getAttentionId, EamAttention::getModifyTime,(v1, v2)->v2));
        Map<Long, Integer> attentionSource = attentionVo.getAttentionList().stream().collect(
                Collectors.toMap(EamAttention::getAttentionId, EamAttention::getSource, (k1, k2) -> k1));

        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        //关注的视图
        this.fillMyAttentionDiagramInfo(attentionVo.getDiagramList(), req, categoryIds, attentionSort, userInfoMap, result,attentionSource);
        //关注的方案
        this.fillMyAttentionPlanInfo(attentionVo.getPlanDesignList(), req, categoryIds, attentionSort, userInfoMap, result,attentionSource);
        Collections.sort(result, (PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int)(o2.getAttentionTime() - o1.getAttentionTime()));
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    private void fillMyAttentionDiagramInfo(List<ESDiagram> diagramList, MineAssetsReq req, Set<Long> categoryIds
            , Map<Long, Long> attentionSort, Map<String, UserInfo> userInfoMap, List<PublishedDiagramPlanVO> result, Map<Long, Integer> attentionSource) {
        if (CollectionUtils.isEmpty(diagramList)) {
            return;
        }
        for (ESDiagram diagram : diagramList) {
            Boolean matchFilter = this.matchFilter(req, diagram.getName(), categoryIds, diagram.getDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            publishedDiagramPlanVO.setDiagram(diagram);
            publishedDiagramPlanVO.setAssetType(AssetType.DIAGRAM);
            publishedDiagramPlanVO.setAttentionTime(attentionSort.get(diagram.getId()));
            publishedDiagramPlanVO.setIsAttention(DiagramConstant.IS_ATTENTION);
            publishedDiagramPlanVO.setCreator(userInfoMap.get(diagram.getCreator()));
            publishedDiagramPlanVO.setAttentionSource(attentionSource.get(diagram.getId()));
            result.add(publishedDiagramPlanVO);
        }
    }

    private void fillMyAttentionPlanInfo(List<PlanDesignInstance> planDesignList, MineAssetsReq req, Set<Long> categoryIds
            , Map<Long, Long> attentionSort, Map<String, UserInfo> userInfoMap, List<PublishedDiagramPlanVO> result, Map<Long, Integer> attentionSource) {
        if (CollectionUtils.isEmpty(planDesignList)) {
            return;
        }
        Map<String, List<PlanDesignInstance>> planHistoryMap = this.queryPlanHistory(planDesignList);
        for (PlanDesignInstance plan : planDesignList) {
            Boolean matchFilter = this.matchFilter(req, plan.getName(), categoryIds, plan.getAssetsDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            publishedDiagramPlanVO.setCreator(userInfoMap.get(plan.getCreatorCode()));
            String dirType = plan.getDirType() == null ? "" : plan.getDirType().toString();
            String key = plan.getBusinessKey() + dirType;
            if (planHistoryMap.containsKey(key)) {
                plan.setVersion(planHistoryMap.get(key).size());
            }
            publishedDiagramPlanVO.setPlanDesignInstance(plan);
            publishedDiagramPlanVO.setAssetType(AssetType.SCHEME);
            publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
            publishedDiagramPlanVO.setIsAttention(DiagramConstant.IS_ATTENTION);
            publishedDiagramPlanVO.setAttentionTime(attentionSort.get(plan.getId()));
            publishedDiagramPlanVO.setAttentionSource(attentionSource.get(plan.getId()));
            result.add(publishedDiagramPlanVO);
        }
    }

    private ESDiagramDirPlanVO queryMyRecentView(MineAssetsReq req, Set<Long> categoryIds) {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        List<EamRecentlyView> recentlyViews = recentlyViewSvc.getDesignRecentlyView();
        if (CollectionUtils.isEmpty(recentlyViews)) {
            return esDiagramDirPlanVO;
        }
        Map<Integer, List<EamRecentlyView>> recentlyViewGroupMap = recentlyViews.stream().collect(Collectors.groupingBy(EamRecentlyView::getViewType));
        //最近查看的视图
        if (recentlyViewGroupMap.containsKey(1)) {
            this.fillMyRecentViewDiagramInfo(recentlyViewGroupMap, req, categoryIds, result);
        }
        //最近查看的方案
        if (recentlyViewGroupMap.containsKey(2)) {
            this.fillMyRecentViewPlanInfo(recentlyViewGroupMap, req, categoryIds, result);
        }
        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getViewTime() - o1.getViewTime()));
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    private void fillMyRecentViewDiagramInfo(Map<Integer, List<EamRecentlyView>> recentlyViewGroupMap, MineAssetsReq req,
                                             Set<Long> categoryIds, List<PublishedDiagramPlanVO> result) {
        List<EamRecentlyView> recentlyViewDiagrams = recentlyViewGroupMap.get(1).stream()
                .filter(item -> item.getDiagramId() != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(recentlyViewDiagrams)) {
            return;
        }
        Set<Long> diagramIds = recentlyViewDiagrams.stream().map(EamRecentlyView::getDiagramId).collect(Collectors.toSet());
        BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
        diagramQuery.must(QueryBuilders.termsQuery("id", diagramIds));
        diagramQuery.must(QueryBuilders.termQuery("status", 1));
        diagramQuery.must(QueryBuilders.termQuery("domainId", SysUtil.getCurrentUserInfo().getDomainId()));
        Page<ESDiagram> diagramPage = diagramApiClient.selectListByQuery(1, 3000, diagramQuery);
        if (CollectionUtils.isEmpty(diagramPage.getData())) {
            return;
        }
        List<ESDiagram> diagramList = diagramPage.getData();
        Map<String, UserInfo> userInfoMap = this.queryUserInfo(diagramList.stream().map(ESDiagram::getCreator).distinct().collect(Collectors.toList()));
        List<Long> myAttentionDiagramIds = attentionSvc.getMyAttentionDiagramIds();
        Map<Long, Long> diagramViewtimeMap = recentlyViewDiagrams.stream().collect(Collectors.toMap(EamRecentlyView::getDiagramId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        for (ESDiagram diagram : diagramList) {
            Boolean matchFilter = this.matchFilter(req, diagram.getName(), categoryIds, diagram.getDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            publishedDiagramPlanVO.setDiagram(diagram);
            publishedDiagramPlanVO.setAssetType(AssetType.DIAGRAM);
            publishedDiagramPlanVO.setViewTime(diagramViewtimeMap.get(diagram.getId()));
            if (myAttentionDiagramIds.contains(diagram.getId())) {
                publishedDiagramPlanVO.setIsAttention(DiagramConstant.IS_ATTENTION);
            }
            publishedDiagramPlanVO.setCreator(userInfoMap.get(diagram.getCreator()));
            result.add(publishedDiagramPlanVO);
        }
    }

    private void fillMyRecentViewPlanInfo(Map<Integer, List<EamRecentlyView>> recentlyViewGroupMap, MineAssetsReq req,
                                          Set<Long> categoryIds, List<PublishedDiagramPlanVO> result) {
        List<EamRecentlyView> recentlyViewPlans = recentlyViewGroupMap.get(2).stream()
                .filter(item -> item.getPlanId() != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(recentlyViewPlans)) {
            return;
        }
        List<Long> planIds = recentlyViewPlans.stream().map(EamRecentlyView::getPlanId).distinct().collect(Collectors.toList());
        List<PlanDesignInstance> planDesignList = planDesignInstanceService.findPlanDesignListByPlanIds(planIds.toArray(new Long[planIds.size()]), null);
        if (CollectionUtils.isEmpty(planDesignList)) {
            return;
        }
        List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
        Map<Long, Long> planViewtimeMap = recentlyViewPlans.stream().collect(Collectors.toMap(EamRecentlyView::getPlanId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        Map<String, List<PlanDesignInstance>> planHistoryMap = this.queryPlanHistory(planDesignList);
        Map<String, UserInfo> userInfoMap = this.queryUserInfo(planDesignList.stream().map(PlanDesignInstance::getCreatorCode).distinct().collect(Collectors.toList()));
        for (PlanDesignInstance plan : planDesignList) {
            Boolean matchFilter = this.matchFilter(req, plan.getName(), categoryIds, plan.getAssetsDirId());
            if (Boolean.TRUE.equals(matchFilter)) {
                continue;
            }
            PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
            publishedDiagramPlanVO.setCreator(userInfoMap.get(plan.getCreatorCode()));
            String dirType = plan.getDirType() == null ? "" : plan.getDirType().toString();
            String key = plan.getBusinessKey() + dirType;
            if (planHistoryMap.containsKey(key)) {
                plan.setVersion(planHistoryMap.get(key).size());
            }
            publishedDiagramPlanVO.setPlanDesignInstance(plan);
            publishedDiagramPlanVO.setAssetType(AssetType.SCHEME);
            publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
            publishedDiagramPlanVO.setViewTime(planViewtimeMap.get(plan.getId()));
            if (myAttentionPlans.contains(plan.getId())) {
                publishedDiagramPlanVO.setIsAttention(DiagramConstant.IS_ATTENTION);
            }
            result.add(publishedDiagramPlanVO);
        }
    }

    private Boolean matchFilter(MineAssetsReq req, String sourceName, Set<Long> categoryIds, Long sourceDirId) {
        if (!this.likeSatisfy(req.getLike(), sourceName)) {
            return true;
        }
        if (req.getRootId() == null) {
            return false;
        }
        return !categoryIds.contains(sourceDirId);
    }

    /**
     * 是否满足模糊查询条件
     * @param like 查询关键字
     * @param name 资产名称
     * @return
     */
    private Boolean likeSatisfy(String like, String name) {
        if (StringUtils.isBlank(like)) {
            return true;
        }
        return Pattern.compile(Pattern.quote(like), Pattern.CASE_INSENSITIVE).matcher(name).find();
    }

    /**
     * 我关注的视图
     * @return
     */
    private Map<String, ESDiagram> queryMyAttentionDiagramMap() {
        Map<String, ESDiagram> myAttentionDiagramMap = new ConcurrentHashMap<>();
        List<Long> attentionDiagramIds = attentionSvc.getMyAttentionDiagramIds();
        if (CollectionUtils.isEmpty(attentionDiagramIds)) {
            return myAttentionDiagramMap;
        }
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termsQuery("id", attentionDiagramIds));
        Page<ESDiagram> esDiagramPage = esDiagramSvc.selectListByQuery(1, 2000, boolQuery);
        if (!CollectionUtils.isEmpty(esDiagramPage.getData())) {
            myAttentionDiagramMap = esDiagramPage.getData().stream().collect(Collectors.toMap(ESDiagram::getDEnergy, e -> e));
        }
        return myAttentionDiagramMap;
    }

    private Map<String, List<PlanDesignInstance>> queryPlanHistory(List<PlanDesignInstance> planDesignList) {
        Map<String, List<PlanDesignInstance>> map = new ConcurrentHashMap<>();
        List<PlanDesignInstance> list = planDesignList.stream().filter(plan -> StringUtils.isNotBlank(plan.getBusinessKey())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        List<MinePlanQueryVo> minePlanQueryVos = new ArrayList<>();
        List<String> statusList = Lists.newArrayList(PlanStatusEnum.published.name(), PlanStatusEnum.history.name());
        for (PlanDesignInstance planDesignInstance : list) {
            minePlanQueryVos.add(new MinePlanQueryVo(planDesignInstance.getBusinessKey(), planDesignInstance.getDirType(), statusList));
        }
        List<PlanDesignInstance> planDesignInstances = planDesignInstanceService.findPlanInstanceList(minePlanQueryVos);
        if (!CollectionUtils.isEmpty(planDesignInstances)) {
            for (PlanDesignInstance instance : planDesignInstances) {
                String dirType = instance.getDirType() == null ? "" : instance.getDirType().toString();
                String key = instance.getBusinessKey() + dirType;
                List<PlanDesignInstance> l = map.getOrDefault(key, new ArrayList<>());
                l.add(instance);
                map.put(key, l);
            }
        }
        return map;
    }

    private Map<String, UserInfo> queryUserInfo(List<String> loginCodes) {
        Map<String, UserInfo> userInfoMap = new ConcurrentHashMap<>();
        CSysUser cdt = new CSysUser();
        cdt.setLoginCodes(loginCodes.toArray(new String[loginCodes.size()]));
        List<UserInfo> userInfos = userApiSvc.getUserInfoByCdt(cdt, true);
        if (!CollectionUtils.isEmpty(userInfos)) {
            userInfoMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getLoginCode, e -> e));
        }
        return userInfoMap;
    }

    @Override
    public ESDiagramDirPlanVO getAllMineAttention() throws ParseException {
        AttentionDto attentionDto = new AttentionDto();
        attentionDto.setUserId(SysUtil.getCurrentUserInfo().getId());
        AttentionVo mineFocus = attentionSvc.getMineFocus(1,2000,attentionDto);
        return queryMyAllAttention(mineFocus);
    }

    @Override
    public ESDiagramDirPlanVO getDesignDiagramAndPlan() throws ParseException {
        RecentlyViewBo recentlyViewList = recentlyViewSvc.getDesignRecentlyDiagram();
        AttentionVo buildAssets = new AttentionVo();
        buildAssets.setRecentlyViewBo(recentlyViewList);
        return  queryMyAllRecentView(buildAssets);
    }


    @Override
    public ESDiagramDirPlanVO getAllRecentlyDiagramAndPlan() throws ParseException {
        RecentlyViewBo recentlyViewList = recentlyViewSvc.getAllRecentlyDiagram();
        AttentionVo buildAssets = new AttentionVo();
        buildAssets.setRecentlyViewBo(recentlyViewList);
        return queryMyAllRecentView(buildAssets);
    }
    @Autowired
    private ESDiagramSvc diagramService;
    @Override
    public Map<String, Long> getCount() throws ParseException {
        Map<String, Long> result = new HashMap<>();
        // 收藏
//        AttentionDto attentionDto = new AttentionDto();
//        attentionDto.setUserId(SysUtil.getCurrentUserInfo().getId());
//        AttentionVo mineFocus = attentionSvc.getMineFocus(1,2000,attentionDto);
//        ESDiagramDirPlanVO esDiagramDirPlanVO =queryMyAllAttention(mineFocus);
//        long attentionNum = esDiagramDirPlanVO.getPublishedDiagramPlanList().size();
        // 最近查看
        List<EamRecentlyView>  recentlyViewList= recentlyViewSvc.getAllRecentlyList();
        if (recentlyViewList == null || recentlyViewList.size() <= 0) {
            return Collections.emptyMap();
        }
        //最近查看的视图
        Map<Long, Long> diagramMap = recentlyViewList.stream().filter(item -> item.getDiagramId() != null).collect(Collectors.toMap(EamRecentlyView::getDiagramId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        //最近查看的方案
        Map<Long, Long> planMap = recentlyViewList.stream().filter(item -> item.getPlanId() != null).collect(Collectors.toMap(EamRecentlyView::getPlanId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        long redactNum = 0L;
        List<PlanDesignInstance> planDesignList = Collections.emptyList();
        if (!CollectionUtils.isEmpty(planMap)) {
            Set<Long> planIds = planMap.keySet();
           planDesignList = planDesignInstanceService.findAllPlanDesignListByPlanIds(planIds.toArray(new Long[0]), null);
           planDesignList = planDesignList.stream().filter(e -> !BinaryUtils.isEmpty(planMap.get(e.getId()))).collect(Collectors.toList());
            redactNum = planDesignList.size();
        }
        List<ESDiagram> diagramList = Collections.emptyList();
        List<Long> diagramIdList = recentlyViewList.stream().
                filter(view -> !BinaryUtils.isEmpty(view.getViewType()) && view.getViewType() == 1).map(EamRecentlyView :: getDiagramId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(diagramIdList)) {
            CVcDiagram cVcDiagram = new CVcDiagram();
            cVcDiagram.setIds(diagramIdList.toArray(new Long[0]));
            List<ESDiagram>  esDiagramList = diagramService.queryESDiagramList(1l, cVcDiagram, "");
            List<String> diagramIds = esDiagramList.stream().map(item -> item.getDEnergy()).collect(Collectors.toList());
            Map<String, Long> diagramIds1 = getDiagramIds(diagramIds);
            diagramList = esDiagramList.stream().filter(e -> !BinaryUtils.isEmpty(diagramMap.get(diagramIds1.get(e.getDEnergy())))).collect(Collectors.toList());
            redactNum = redactNum + diagramList.size();
        }
        // 最近编辑
        List<EamRecentlyView> designRecentlyList = recentlyViewList.stream()
                .filter(e->!BinaryUtils.isEmpty(e.getViewArchitectureType())&&e.getViewArchitectureType().equals(1)).collect(Collectors.toList());
        //最近查看的视图
        Map<Long, Long> diagramDesignMap = designRecentlyList.stream().filter(item -> item.getDiagramId() != null).collect(Collectors.toMap(EamRecentlyView::getDiagramId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        //最近查看的方案
        Map<Long, Long> planDesignMap = designRecentlyList.stream().filter(item -> item.getPlanId() != null).collect(Collectors.toMap(EamRecentlyView::getPlanId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        long checkCount = planDesignList.stream().filter(e -> !BinaryUtils.isEmpty(planDesignMap.get(e.getId()))).count();
        long count = diagramList.stream().filter(e -> !BinaryUtils.isEmpty(diagramDesignMap.get(e.getId()))).count();

//        result.put("attentionCount", attentionNum);
        result.put("checkCount", checkCount+count);
        result.put("redactCount", redactNum);
        return result;
    }

    private ESDiagramDirPlanVO queryMyAllRecentView(AttentionVo buildAssets) throws ParseException {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        List<EamRecentlyView> recentlyView = null;
        if (buildAssets.getRecentlyViewBo() != null && buildAssets.getRecentlyViewBo().getRecentlyViewList() != null && buildAssets.getRecentlyViewBo().getRecentlyViewList().size() >= 1) {
            List<EamRecentlyView> recentlyViewList = buildAssets.getRecentlyViewBo().getRecentlyViewList();
            recentlyView = recentlyViewList;
        }

        if (recentlyView == null || recentlyView.size() <= 0) {
            return esDiagramDirPlanVO;
        }
        //最近查看的视图
        Map<Long, Long> diagramMap = recentlyView.stream().filter(item -> item.getDiagramId() != null).collect(Collectors.toMap(EamRecentlyView::getDiagramId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        //最近查看的方案
        Map<Long, Long> planMap = recentlyView.stream().filter(item -> item.getPlanId() != null).collect(Collectors.toMap(EamRecentlyView::getPlanId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        Set<Long> planIds = planMap.keySet();
        if (buildAssets.getRecentlyViewBo() != null && !CollectionUtils.isEmpty(buildAssets.getRecentlyViewBo().getDiagramDTOList())) {
            List<ESSimpleDiagramDTO> diagramList = buildAssets.getRecentlyViewBo().getDiagramDTOList();

            List<String> diagramIds = buildAssets.getRecentlyViewBo().getDiagramDTOList().stream().map(item -> item.getDiagram().getDEnergy()).collect(Collectors.toList());
            Map<String, Long> diagramIdsMap = getDiagramIds(diagramIds);

            for (ESSimpleDiagramDTO esSimpleDiagramDTO : diagramList) {
                ESDiagram diagram = esSimpleDiagramDTO.getDiagram();
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                publishedDiagramPlanVO.setDiagram(diagram);
                publishedDiagramPlanVO.setCreator(esSimpleDiagramDTO.getCreator());
                publishedDiagramPlanVO.setShareRecords(esSimpleDiagramDTO.getShareRecords());
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                Long viewTime = diagramMap.get(diagramIdsMap.get(diagram.getDEnergy()));
                if(viewTime == null){
                    continue;
                }
                publishedDiagramPlanVO.setViewTime(viewTime);
                result.add(publishedDiagramPlanVO);
            }
        }

        if (!CollectionUtils.isEmpty(planIds)) {
            List<PlanDesignInstance> planDesignList = planDesignInstanceService.findAllPlanDesignListByPlanIds(planIds.toArray(new Long[0]), null);
            List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
            if (!CollectionUtils.isEmpty(planDesignList)) {
                CSysUser user = new CSysUser();
                Set<String> loginCodes = planDesignList.stream().map(PlanDesignInstance :: getCreatorCode).collect(Collectors.toSet());
                user.setLoginCodes(loginCodes.toArray(new String[0]));
                List<SysUser> sysUser = userApiSvc.getSysUserByCdt(user);
                Map<String, SysUser> loginCodeMap = sysUser.stream().collect(Collectors.toMap(SysUser::getLoginCode, item -> item));
                for (PlanDesignInstance plan : planDesignList) {
                    PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                    publishedDiagramPlanVO.setCreator(loginCodeMap.get(plan.getCreatorCode()) != null ?loginCodeMap.get(plan.getCreatorCode()) :null);
                    publishedDiagramPlanVO.setPlanDesignInstance(plan);
                    publishedDiagramPlanVO.setType(Constants.PLAN);
                    publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                    Long viewTime = planMap.get(plan.getId());
                    if(viewTime == null){
                        continue;
                    }
                    publishedDiagramPlanVO.setViewTime(viewTime);
                    if (myAttentionPlans.contains(plan.getId())) {
                        publishedDiagramPlanVO.setIsAttention(1);
                    }
                    result.add(publishedDiagramPlanVO);
                }
            }
        }
        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getViewTime() - o1.getViewTime()));
        timeFormatConversion(result);
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    @Override
    public List<PublishedDiagramPlanVO> findMyPublishList(SysUser user) {
        if (user == null || StringUtils.isEmpty(user.getLoginCode())) {
            throw new BusinessException("用户信息不能为空!");
        }
        // 获取用户信息
        CSysUser userInfo = new CSysUser();
        userInfo.setLoginCodeEqual(user.getLoginCode());
        List<SysUser> sysUser = userApiSvc.getSysUserByCdt(userInfo);

        List<DirRelationPlan> dirRelationPlanList = dirRelationPlanService.findUserPublishList(user.getLoginCode());
        List<PublishedDiagramPlanVO> publishedDiagramPlanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dirRelationPlanList)) {
            Set<Long> planIds = dirRelationPlanList.stream().map(dirRelationPlan -> dirRelationPlan.getPlanId()).collect(Collectors.toSet());
            if (!CollectionUtils.isEmpty(planIds)) {
                List<PlanDesignInstance> planDesignList = planDesignInstanceService.findPlanDesignListByPlanIds(planIds.toArray(new Long[0]), null);
                List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
                if (!CollectionUtils.isEmpty(planDesignList)) {
                    planDesignList.forEach(plan -> {
                        PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                        if (!CollectionUtils.isEmpty(sysUser)) {
                            publishedDiagramPlanVO.setCreator(sysUser.get(0));
                        }
                        publishedDiagramPlanVO.setPlanDesignInstance(plan);
                        publishedDiagramPlanVO.setType(Constants.PLAN);
                        publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                        if (myAttentionPlans.contains(plan.getId())) {
                            publishedDiagramPlanVO.setIsAttention(1);
                        }
                        publishedDiagramPlanList.add(publishedDiagramPlanVO);
                    });
                }
            }
        }

        // 封装发布的视图
        CVcDiagram cVcDiagram = new CVcDiagram();
        cVcDiagram.setDirType(Constants.DIR_TYPE);
        cVcDiagram.setIsOpen(Constants.IS_OPEN);
        cVcDiagram.setCreatorEqual(user.getLoginCode());
        Page<ESSimpleDiagramDTO> page = esDiagramSvc.queryESDiagramInfoPage(user.getDomainId(), 1, 1000, cVcDiagram, null);
        List<ESSimpleDiagramDTO> diagramList = new ArrayList<>();
        if (page != null && !CollectionUtils.isEmpty(page.getData())) {
            diagramList = page.getData();
        }
        if (!CollectionUtils.isEmpty(diagramList)) {
            diagramList.forEach(diagram -> {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                if (!CollectionUtils.isEmpty(sysUser)) {
                    publishedDiagramPlanVO.setCreator(sysUser.get(0));
                }
                publishedDiagramPlanVO.setDiagram(diagram.getDiagram());
                publishedDiagramPlanVO.setCreator(diagram.getCreator());
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                publishedDiagramPlanList.add(publishedDiagramPlanVO);
            });
        }

        // 按时间降序排序
        Collections.sort(publishedDiagramPlanList, (PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int)(o2.getModifyTime() - o1.getModifyTime()));

        return publishedDiagramPlanList;
    }

    @Override
    public String getDirName(DirVo dirVo) {
        if (dirVo.getPlanId() != null) {
            //根据planId查询关联表，查看视图的发布位置
            DirRelationPlan dirRelationPlanVo = new DirRelationPlan();
            dirRelationPlanVo.setPlanId(dirVo.getPlanId());
            List<DirRelationPlan> dirRelationPlans = dirRelationPlanDao.getListByCdt(dirRelationPlanVo);
            if (CollectionUtils.isEmpty(dirRelationPlans)) {
                return null;
            }
            DirRelationPlan dirRelationPlan = dirRelationPlans.get(0);
            return categorySvc.getById(dirRelationPlan.getDirId(), LibType.DESIGN).getDirName();
        }

        if (dirVo.getDirId() != null) {
            return categorySvc.getById(dirVo.getDirId(), LibType.DESIGN).getDirName();
        }

        return null;
    }

    @Override
    public String getHostSystemByPlanId(Long planId) {
        if (planId == null) {
            throw new BusinessException("方案信息不能为空!");
        }
        PlanDesignInstance planDesign = planDesignInstanceDao.getById(planId);
        if (planDesign == null || CollectionUtils.isEmpty(planDesign.getCiCodeList())) {
            return null;
        }
        List<String> ciNameList = new ArrayList<>();
        if (planDesign.getCiCodeList() == null || StringUtils.isBlank(planDesign.getCiCodeList().get(0))) {
            return null;
        }
        planDesign.getCiCodeList().forEach(str -> {
            ESCISearchBean bean = new ESCISearchBean();
            CCcCi cdt = new CCcCi();
            cdt.setCiCode(str);
            bean.setCdt(cdt);
            CiGroupPage ciGroupPage = ciSwitchSvc.queryPageBySearchBean(bean, false, LibType.DESIGN);
            CcCiInfo ci = null;
            if (ciGroupPage != null && !CollectionUtils.isEmpty(ciGroupPage.getData())) {
                ci =  ciGroupPage.getData().get(0);
            }
            if (ci != null && ci.getCi() != null && !StringUtils.isEmpty(ci.getCi().getCiLabel())) {
                String ciName = ci.getCi().getCiLabel().replace("[", "").replace("]", "").replaceAll("\"", "");
                ciNameList.add(ciName);
            }
        });
        if (!CollectionUtils.isEmpty(ciNameList)) {
            return StringUtils.join(ciNameList, ", ");
        }
        return null;
    }

    @Deprecated
    private ESDiagramDirPlanVO queryMyRecentView(AttentionVo buildAssets) {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        List<EamRecentlyView> recentlyView = recentlyViewSvc.getRecentlyView(null);
        if (recentlyView == null || recentlyView.size() <= 0) {
            return esDiagramDirPlanVO;
        }
        //最近查看的视图
        Map<Long, Long> diagramMap = recentlyView.stream().filter(item -> item.getDiagramId() != null).collect(Collectors.toMap(EamRecentlyView :: getDiagramId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        //最近查看的方案
        Map<Long, Long> planMap = recentlyView.stream().filter(item -> item.getPlanId() != null).collect(Collectors.toMap(EamRecentlyView :: getPlanId, EamRecentlyView::getModifyTime,(k1, k2)->k2));
        Set<Long> planIds = planMap.keySet();


        if (!CollectionUtils.isEmpty(buildAssets.getDiagramList())) {
            List<ESDiagram> diagramList = buildAssets.getDiagramList();

            List<String> diagramIds = buildAssets.getDiagramList().stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
            Map<String, Long> diagramIdsMap = getDiagramIds(diagramIds);

            for (ESDiagram each : diagramList) {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                publishedDiagramPlanVO.setDiagram(each);
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                publishedDiagramPlanVO.setViewTime(diagramMap.get(diagramIdsMap.get(each.getDEnergy())));
                result.add(publishedDiagramPlanVO);
            }
        }

        if (!CollectionUtils.isEmpty(planIds)) {
            List<PlanDesignInstance> planDesignList = planDesignInstanceService.findPlanDesignListByPlanIds(planIds.toArray(new Long[planIds.size()]), null);
            List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
            if (!CollectionUtils.isEmpty(planDesignList)) {
                CSysUser user = new CSysUser();
                user.setLoginCodeEqual(SysUtil.getCurrentUserInfo().getLoginCode());
                List<SysUser> sysUser = userApiSvc.getSysUserByCdt(user);
                planDesignList.forEach(plan -> {
                    PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                    if (!CollectionUtils.isEmpty(sysUser)) {
                        publishedDiagramPlanVO.setCreator(sysUser.get(0));
                    }
                    if (Objects.equals(plan.getAssetsType(), Constants.ASSETS) && !StringUtils.isEmpty(plan.getBusinessKey())) {
                        //查询最新版本
                        Page<PlanDesignInstance> planInstancePage = planDesignInstanceService.findPlanInstanceList(plan.getBusinessKey(),
                                Lists.newArrayList(PlanStatusEnum.published.name(), PlanStatusEnum.history.name()), plan.getDirType());
                        if (planInstancePage != null && !CollectionUtils.isEmpty(planInstancePage.getData())) {
                            plan.setVersion(planInstancePage.getData().size());
                        }
                    }
                    publishedDiagramPlanVO.setPlanDesignInstance(plan);
                    publishedDiagramPlanVO.setType(Constants.PLAN);
                    publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                    publishedDiagramPlanVO.setViewTime(planMap.get(plan.getId()));
                    if (myAttentionPlans.contains(plan.getId())) {
                        publishedDiagramPlanVO.setIsAttention(1);
                    }
                    result.add(publishedDiagramPlanVO);
                });
            }
        }

        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getViewTime() - o1.getViewTime()));
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    @Deprecated
    private ESDiagramDirPlanVO queryMyPublished(AttentionVo buildAssets) {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<PublishedDiagramPlanVO> result = new ArrayList<>();

        List<Long> attentionDiagramIds = attentionSvc.getMyAttentionDiagramIds();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termsQuery("id", attentionDiagramIds));
        Page<ESDiagram> esDiagramPage = esDiagramSvc.selectListByQuery(1, 2000, boolQuery);
        List<ESDiagram> data = esDiagramPage.getData();
        List<String> myAttentionDiagramIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(data)) {
            myAttentionDiagramIds = data.stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
        }
        if (buildAssets.getDiagramList() != null && buildAssets.getDiagramList().size() >= 1) {
            List<ESDiagram> diagramList = buildAssets.getDiagramList();
            for (ESDiagram each : diagramList) {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                if (myAttentionDiagramIds.contains(each.getDEnergy())) {
                    each.setIsAttention(1);
                }
                publishedDiagramPlanVO.setDiagram(each);
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                publishedDiagramPlanVO.setModifyTime(each.getModifyTime());
                result.add(publishedDiagramPlanVO);
            }
        }

        //下面处理我发布的方案
        List<PlanDesignInstance> planDesignList = planDesignInstanceService.queryMyPublishPlan();
        List<Long> myAttentionPlans = attentionSvc.getMyAttentionPlans();
        if (!CollectionUtils.isEmpty(planDesignList)) {
            CSysUser user = new CSysUser();
            user.setLoginCodeEqual(SysUtil.getCurrentUserInfo().getLoginCode());
            List<SysUser> sysUser = userApiSvc.getSysUserByCdt(user);
            planDesignList.forEach(plan -> {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                if (!CollectionUtils.isEmpty(sysUser)) {
                    publishedDiagramPlanVO.setCreator(sysUser.get(0));
                }
                if (Objects.equals(plan.getAssetsType(), Constants.ASSETS) && !StringUtils.isEmpty(plan.getBusinessKey())) {
                    //查询最新版本
                    Page<PlanDesignInstance> planInstancePage = planDesignInstanceService.findPlanInstanceList(plan.getBusinessKey(),
                            Lists.newArrayList(PlanStatusEnum.published.name(), PlanStatusEnum.history.name()), plan.getDirType());
                    if (planInstancePage != null && !CollectionUtils.isEmpty(planInstancePage.getData())) {
                        plan.setVersion(planInstancePage.getData().size());
                    }
                }
                publishedDiagramPlanVO.setPlanDesignInstance(plan);
                publishedDiagramPlanVO.setType(Constants.PLAN);
                publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                if (myAttentionPlans.contains(plan.getId())) {
                    publishedDiagramPlanVO.setIsAttention(1);
                }
                result.add(publishedDiagramPlanVO);
            });
        }
        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getModifyTime() - o1.getModifyTime()));
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    private ESDiagramDirPlanVO queryMyAllAttention(AttentionVo mineFocus) throws ParseException {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<EamAttention> attentionList = mineFocus.getAttentionList();
        if (attentionList == null || attentionList.size() <= 0) {
            return new ESDiagramDirPlanVO();
        }
        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        Map<Long, Long> attentionSort = attentionList.stream().collect(Collectors.toMap(EamAttention::getAttentionId, EamAttention::getModifyTime,(v1, v2)->v2));
        if (mineFocus.getDiagramList() != null && mineFocus.getDiagramList().size() >= 1) {
            List<ESDiagram> diagramList = mineFocus.getDiagramList();
            List<String> creatorCodes = diagramList.stream().map(ESDiagram::getCreator).distinct().collect(Collectors.toList());
            Map<String, UserInfo> userMap = this.queryUserInfo(creatorCodes);
            List<String> diagramIds = mineFocus.getDiagramList().stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
            Map<String, Long> diagramMap = getDiagramIds(diagramIds);
            for (ESDiagram each : diagramList) {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                if (userMap.containsKey(each.getCreator())) {
                    publishedDiagramPlanVO.setCreator(userMap.get(each.getCreator()));
                }
                publishedDiagramPlanVO.setDiagram(each);
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                publishedDiagramPlanVO.setAssetType(AssetType.DIAGRAM);
                publishedDiagramPlanVO.setAttentionTime(attentionSort.get(diagramMap.get(each.getDEnergy())));
                publishedDiagramPlanVO.setUpdateTime(each.getModifyTime());
                publishedDiagramPlanVO.setIsAttention(1);
                result.add(publishedDiagramPlanVO);
            }
        }

        //查询关注类型是方案的id集合
        List<EamAttention> planAttention = attentionList.stream().filter(item -> item.getAttentionType().equals(3)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(planAttention)) {
            List<Long> planIds = planAttention.stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
            List<PlanDesignInstance> planDesignList = planDesignInstanceService.getByIds(planIds);
            if (!CollectionUtils.isEmpty(planDesignList)) {
                List<String> creatorCodes = planDesignList.stream().map(BaseEntity::getCreatorCode).distinct().collect(Collectors.toList());
                Map<String, UserInfo> userMap = this.queryUserInfo(creatorCodes);
                planDesignList.forEach(plan -> {
                    PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                    if (userMap.containsKey(plan.getCreatorCode())) {
                        publishedDiagramPlanVO.setCreator(userMap.get(plan.getCreatorCode()));
                    }
                    publishedDiagramPlanVO.setPlanDesignInstance(plan);
                    publishedDiagramPlanVO.setType(Constants.PLAN);
                    publishedDiagramPlanVO.setAssetType(AssetType.SCHEME);
                    publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                    publishedDiagramPlanVO.setIsAttention(1);
                    publishedDiagramPlanVO.setAttentionTime(attentionSort.get(plan.getId()));
                    publishedDiagramPlanVO.setUpdateTime(plan.getModifyTime());
                    result.add(publishedDiagramPlanVO);
                });
            }
        }
        // 资产ci
        List<EamAttention> ciAttentionList = attentionList.stream().filter(item -> item.getAttentionType().equals(4)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ciAttentionList)) {
            Map<String, Long> ciModifyTimeMap = new HashMap<>();
            List<String> designCiCodes = new ArrayList<>();
            List<String> privateCiCodes = new ArrayList<>();
            Set<Long> configIds = new HashSet<>();
            for (EamAttention each : ciAttentionList) {
                if(!BinaryUtils.isEmpty(each.getAttentionCode())){
                    ciModifyTimeMap.put(each.getAttentionCode(), each.getModifyTime());
                }
                if(each.getSource().equals(1)){
                    designCiCodes.add(each.getAttentionCode());
                }else{
                    privateCiCodes.add(each.getAttentionCode());
                }
                if(!BinaryUtils.isEmpty(each.getConfigId())){
                    configIds.add(each.getConfigId());
                }
            }
            List<ESCIInfo> ciList = new ArrayList<>(ciSwitchSvc.getCiByCodes(designCiCodes, null, LibType.DESIGN));
            ciList.addAll(ciSwitchSvc.getCiByCodes(privateCiCodes, SysUtil.getCurrentUserInfo().getLoginCode(), LibType.PRIVATE));
            if (!CollectionUtils.isEmpty(ciList)) {
                List<ESCIClassInfo> classInfos = ciClassApiSvc.selectCiClassByIds(ciList.stream().map(CcCi::getClassId).collect(Collectors.toList()));
                Map<Long, String> classIdByCode = classInfos.stream().collect(Collectors.toMap(CcCiClass::getId, CcCiClass::getClassCode, (k1, k2) -> k1));
                List<AppSquareConfig> configList = squareConfigSvc.getByIdsWithoutAuth(configIds);
                Map<String, AppSquareConfig> configMap = configList.stream().collect(Collectors.toMap(AppSquareConfig::getClassCode, e -> e, (k1, k2) -> k2));
                Set<String> creates = ciList.stream().map(CcCi::getCreator).collect(Collectors.toSet());
                Map<String, UserInfo> userMap = this.queryUserInfo(new ArrayList<>(creates));
                ciList.forEach(esciInfo -> {
                    PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                    if (userMap.containsKey(esciInfo.getCreator())) {
                        publishedDiagramPlanVO.setCreator(userMap.get(esciInfo.getCreator()));
                    }
                    AssetCiDetailInfoDTO assetCiDetailInfoDTO = new AssetCiDetailInfoDTO();
                    assetCiDetailInfoDTO.setEsciInfo(esciInfo);
                    String classCode = classIdByCode.get(esciInfo.getClassId());
                    assetCiDetailInfoDTO.setClassCode(classCode);
                    AppSquareConfig conf = configMap.get(classCode);
                    assetCiDetailInfoDTO.setAppSquareId(BinaryUtils.isEmpty(conf) ? 0L : conf.getId());
                    assetCiDetailInfoDTO.setCardName(BinaryUtils.isEmpty(conf)?"":conf.getCardName());
                    if (designCiCodes.contains(esciInfo.getCiCode())) {
                        assetCiDetailInfoDTO.setSource(1);
                    } else if (privateCiCodes.contains(esciInfo.getCiCode())) {
                        assetCiDetailInfoDTO.setSource(0);
                    }

                    publishedDiagramPlanVO.setAssetCiDetailInfoDTO(assetCiDetailInfoDTO);

                    publishedDiagramPlanVO.setType(Constants.CI);
                    publishedDiagramPlanVO.setAssetType(AssetType.CI);
                    publishedDiagramPlanVO.setModifyTime(esciInfo.getModifyTime());
                    publishedDiagramPlanVO.setIsAttention(1);
                    publishedDiagramPlanVO.setAttentionTime(ciModifyTimeMap.get(esciInfo.getCiCode()));
                    publishedDiagramPlanVO.setAttentionTime(esciInfo.getModifyTime());
                    publishedDiagramPlanVO.setUpdateTime(esciInfo.getModifyTime());
                    result.add(publishedDiagramPlanVO);
                });
            }
        }
        result.sort((PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int) (o2.getUpdateTime() - o1.getUpdateTime()));
        List<PublishedDiagramPlanVO> limitResult = result.stream().limit(50).collect(Collectors.toList());
        timeFormatConversion(limitResult);
        esDiagramDirPlanVO.setPublishedDiagramPlanList(limitResult);
        esDiagramDirPlanVO.setAttentionCount(result.size());
        return esDiagramDirPlanVO;
    }

    private <T> void timeFormatConversion(List<T> data) throws ParseException {
        DateFormat fmt =new SimpleDateFormat("yyyyMMddHHmmss");
        DateFormat fmt1 =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        for (T datum : data) {
            if (datum instanceof PublishedDiagramPlanVO) {
                PublishedDiagramPlanVO publishedDiagramPlanVO = (PublishedDiagramPlanVO) datum;
                if (publishedDiagramPlanVO.getViewTime() != null) {
                    String conversionViewTime = publishedDiagramPlanVO.getViewTime()+"";
                    Date parse = fmt.parse(conversionViewTime);
                    publishedDiagramPlanVO.setConversionViewTime(fmt1.format(parse));

                }
                if (publishedDiagramPlanVO.getAttentionTime() != null) {
                    String conversionAttentionTime = publishedDiagramPlanVO.getUpdateTime()+"";
                    Date parse = fmt.parse(conversionAttentionTime);
                    publishedDiagramPlanVO.setConversionUpdate(fmt1.format(parse));
                }
            }
        }
    }

    @Deprecated
    private ESDiagramDirPlanVO queryMyAttention(AttentionVo buildAssets, String like) {
        ESDiagramDirPlanVO esDiagramDirPlanVO = new ESDiagramDirPlanVO();
        List<EamAttention> attentionList = buildAssets.getAttentionList();
        if (attentionList == null || attentionList.size() <= 0) {
            return new ESDiagramDirPlanVO();
        }
        //查询关注类型是方案的id集合
        List<EamAttention> planAttention = attentionList.stream().filter(item -> item.getAttentionType().equals(3)).collect(Collectors.toList());

        List<PublishedDiagramPlanVO> result = new ArrayList<>();
        Map<Long, Long> attentionSort = attentionList.stream().collect(Collectors.toMap(EamAttention::getAttentionId, EamAttention::getModifyTime,(v1, v2)->v2));
        if (buildAssets.getDiagramList() != null && buildAssets.getDiagramList().size() >= 1) {
            List<ESDiagram> diagramList = buildAssets.getDiagramList();
            List<String> diagramIds = buildAssets.getDiagramList().stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
            Map<String, Long> diagramMap = getDiagramIds(diagramIds);

            for (ESDiagram each : diagramList) {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                publishedDiagramPlanVO.setDiagram(each);
                publishedDiagramPlanVO.setType(Constants.DIAGRAM);
                publishedDiagramPlanVO.setAttentionTime(attentionSort.get(diagramMap.get(each.getDEnergy())));
                result.add(publishedDiagramPlanVO);
            }
        }
        List<Long> planIds = planAttention.stream().map(EamAttention::getAttentionId).collect(Collectors.toList());
        List<PlanDesignInstance> planDesignList = planDesignInstanceService.findPlanDesignListByPlanIds(planIds.toArray(new Long[0]), null);
        if (!CollectionUtils.isEmpty(planDesignList)) {
            List<String> creatorCodes = planDesignList.stream().map(BaseEntity::getCreatorCode).collect(Collectors.toList());
            CSysUser user = new CSysUser();
            user.setLoginCodes(creatorCodes.toArray(new String[0]));
            List<SysUser> sysUser = userApiSvc.getSysUserByCdt(user);
            Map<String, SysUser> userMap = sysUser.stream().distinct().collect(Collectors.toMap(SysUser::getLoginCode, item -> item));
            planDesignList.forEach(plan -> {
                PublishedDiagramPlanVO publishedDiagramPlanVO = new PublishedDiagramPlanVO();
                if (!CollectionUtils.isEmpty(sysUser)) {
                    publishedDiagramPlanVO.setCreator(userMap.get(plan.getCreatorCode()));
                }
                if (!StringUtils.isEmpty(plan.getBusinessKey())) {
                    //查询最新版本
                    Page<PlanDesignInstance> planInstancePage = planDesignInstanceService.findPlanInstanceList(plan.getBusinessKey(),
                            Lists.newArrayList(PlanStatusEnum.published.name(), PlanStatusEnum.history.name()), plan.getDirType());
                    if (planInstancePage != null && !CollectionUtils.isEmpty(planInstancePage.getData())) {
                        plan.setVersion(planInstancePage.getData().size());
                    }
                }
                publishedDiagramPlanVO.setPlanDesignInstance(plan);
                publishedDiagramPlanVO.setType(Constants.PLAN);
                publishedDiagramPlanVO.setModifyTime(plan.getModifyTime());
                publishedDiagramPlanVO.setIsAttention(1);
                publishedDiagramPlanVO.setAttentionTime(attentionSort.get(plan.getId()));
                result.add(publishedDiagramPlanVO);
            });
        }
        Collections.sort(result, (PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int)(o2.getAttentionTime() - o1.getAttentionTime()));
        if (like != null) {
            List<PublishedDiagramPlanVO> otherResult = new ArrayList<>();
            for (PublishedDiagramPlanVO publishedDiagramPlanVO : result) {
                if (publishedDiagramPlanVO.getDiagram() != null) {
                    ESDiagram diagram = publishedDiagramPlanVO.getDiagram();
                    if (Pattern.compile(Pattern.quote(like), Pattern.CASE_INSENSITIVE).matcher(diagram.getName()).find()) {
                        otherResult.add(publishedDiagramPlanVO);
                    }
                }else if(publishedDiagramPlanVO.getPlanDesignInstance() != null){
                    PlanDesignInstance planDesignInstance = publishedDiagramPlanVO.getPlanDesignInstance();
                    if (Pattern.compile(Pattern.quote(like), Pattern.CASE_INSENSITIVE).matcher(planDesignInstance.getName()).find()) {
                        otherResult.add(publishedDiagramPlanVO);
                    }
                }
            }
            Collections.sort(otherResult, (PublishedDiagramPlanVO o1, PublishedDiagramPlanVO o2) -> (int)(o2.getAttentionTime() - o1.getAttentionTime()));
            esDiagramDirPlanVO.setPublishedDiagramPlanList(otherResult);
            return esDiagramDirPlanVO;
        }
        esDiagramDirPlanVO.setPublishedDiagramPlanList(result);
        return esDiagramDirPlanVO;
    }

    @Override
    public Boolean movePlane(Long planId, Long targetDirId) {
        BoolQueryBuilder dirRelationQueryBuilder = QueryBuilders.boolQuery();
        dirRelationQueryBuilder.must(QueryBuilders.termQuery("planId",planId));
        DirRelationPlan dirRelationPlan = dirRelationPlanDao.selectOne(dirRelationQueryBuilder);
        dirRelationPlan.setDirId(targetDirId);
        //TODO 这块需要调用伏羲的feign接口根据文件夹id查询文件夹的路径回显信息
        //TODO 等后端字段加上这块放开
        //dirRelationPlan.setEchoName(planDirInfo);
        dirRelationPlanDao.saveOrUpdate(dirRelationPlan);
        return true;
    }

    @Deprecated
    private AttentionVo getBuildAssets(MineAssetsVo mineAssetsVo) {
        MessageUtil.checkEmpty(mineAssetsVo, "mineAssetsVo");
        MessageUtil.checkEmpty(mineAssetsVo.getHandleType(), "handleType");

        SysUser userInfo = SysUtil.getCurrentUserInfo();
        if (HandleTypeEnum.MINE_PUBLISH.getHandleType().equals(mineAssetsVo.getHandleType())) {
            BoolQueryBuilder diagramQuery = QueryBuilders.boolQuery();
            diagramQuery.must(QueryBuilders.termQuery("isOpen", 1));
            diagramQuery.must(QueryBuilders.termQuery("creator.keyword", userInfo.getLoginCode()));
            diagramQuery.must(QueryBuilders.termQuery("historyVersionFlag", 1));
            Page<ESDiagram> diagramPage = diagramApiClient.selectListByQuery(1, 1000, diagramQuery);
            AttentionVo attentionVo = new AttentionVo();
            attentionVo.setDiagramList(diagramPage.getData());
            return attentionVo;
        }else if (HandleTypeEnum.MINE_ATTENTION.getHandleType().equals(mineAssetsVo.getHandleType())) {
            AttentionDto attentionDto = new AttentionDto();
            attentionDto.setUserId(userInfo.getId());
            return attentionSvc.findAttentionList(1, 500, attentionDto);
        } else if (HandleTypeEnum.RECENTLY_VIEW.getHandleType().equals(mineAssetsVo.getHandleType())) {
            EamRecentlyView eamRecentlyView = new EamRecentlyView();
            eamRecentlyView.setUserId(userInfo.getId());
            List<ESDiagram> recentlyViewList = recentlyViewSvc.findRecentlyViewList(eamRecentlyView);
            AttentionVo attentionVo = new AttentionVo();
            attentionVo.setDiagramList(recentlyViewList);
            return attentionVo;
        }
        return null;
    }

    private Map<String, Long> getDiagramIds(List<String> diagram) {
        List<ESDiagram> diagramList = diagramApiClient.selectByIds(diagram, null, null);
        if (CollectionUtils.isEmpty(diagramList)) {
            return new HashMap<>();
        }
        return diagramList.stream().collect(Collectors.toMap(ESDiagram::getDEnergy, ESDiagram::getId));
    }
}
